﻿using Autofac;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics;

namespace IocDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var st = new Stopwatch();

            st.Start();
            var s0 = new TestService();
            s0.Print("new");
            s0.Print("hello world.");
            s0.Print("世界你好");
            st.Stop();
            Console.WriteLine(st.Elapsed);

            // AddSingleton 单例
            // AddScoped 单次请求有效
            // AddTransient 每次都重新建立
            var services = new ServiceCollection();
            services.AddSingleton<ITestService, TestService>();
            ServiceProvider serviceProvider = services.BuildServiceProvider();

            st.Restart();
            var s1 = serviceProvider.GetService<ITestService>();
            s1?.Print("DI");
            s1?.Print("hello world.");
            s1?.Print("世界你好");
            st.Stop();
            Console.WriteLine(st.Elapsed);

            var builder = new ContainerBuilder();
            builder.RegisterType<TestService>().As<ITestService>();
            var autofacContrainer = builder.Build();
            st.Restart();
            var s3 = autofacContrainer.Resolve<ITestService>();
            s3.Print("autofac");
            s3.Print("hello world.");
            s3.Print("世界你好");
            st.Stop();
            Console.WriteLine(st.Elapsed);

            Console.ReadKey();
        }
    }

    internal interface ITestService
    {
        void Print(string strOut);
    }

    internal class TestService : ITestService
    {
        public void Print(string strOut)
        {
            Console.WriteLine(strOut);
        }
    }
}
